package tts.controller.roles;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;

import tts.controller.RedirectAction;
import tts.dao.RolesHome;
import tts.dao.UsersHome;
import tts.model.Roles;
import tts.model.Users;

public class Edit extends RedirectAction{

	//fields
	private static final long serialVersionUID = 7369203581207143122L;
	@Autowired
	private UsersHome usersHome;
	@Autowired
	private RolesHome rolesHome;
	private String roleName;
	private Roles roleEdit;
	private ArrayList<String> strings;

	//get & set
	public String getRoleName() {
		return roleName;
	}
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	public Roles getRoleEdit() {
		return roleEdit;
	}
	public void setRoleEdit(Roles roleEdit) {
		this.roleEdit = roleEdit;
	}
	public ArrayList<String> getStrings() {
		return strings;
	}
	public void setStrings(ArrayList<String> strings) {
		this.strings = strings;
	}

	//methods
	public String edit() {
		try {
			roleEdit.getUsersList().clear();
			for (String s : strings) {
				Users user = usersHome.findByUsername(s);
				this.roleEdit.getUsersList().add(user);
			}
			Collection<Users> allUsers = usersHome.findAll();
			for (Users userAll : allUsers) {
				if (strings.contains(userAll.getUsername())) {
					if (!(userAll.getRolesList().contains(rolesHome.findByRoleName(this.roleName))))
						userAll.getRolesList().add(rolesHome.findByRoleName(this.roleName));
				} else if (userAll.getRolesList().contains(rolesHome.findByRoleName(this.roleName)))
					userAll.getRolesList().remove(rolesHome.findByRoleName(this.roleName));
			}
			rolesHome.update(this.roleName, this.roleEdit);
		} catch (RuntimeException e) {
			addActionError(e.getMessage());
			return ERROR;
		}
		addActionMessage(getText("role.updated"));
		return SUCCESS;
	}
}